package org.rayson.share.transport;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public abstract class NioSelector implements Runnable {

	private final HashSet<SelectionKey> supplementReads;
	private final HashSet<SelectionKey> supplementWrites;
	protected final Selector selector;
	private final String name;

	public NioSelector(final Selector selector, final String name) {
		super();
		this.selector = selector;
		this.name = name;
		supplementReads = new HashSet<>();
		supplementWrites = new HashSet<>();
	}

	public void addReadEvent(final SelectionKey key) {

	}

	public void addWriteEvent(final SelectionKey key) {

	}

	protected void doAccept(final SelectionKey key) {
		// Do nothing.
	}

	protected void doConnect(final SelectionKey key) {
		// Do nothing.
	}

	protected void doRead(final SelectionKey key) {
		// Do nothing.
	}

	protected void doWrite(final SelectionKey key) {
		// Do nothing.
	}

	public String getName() {
		return name;
	}

	protected void pollSupplementReads() {
		if (supplementReads.isEmpty())
			return;
		final List<SelectionKey> readsNow = new ArrayList<>();
		readsNow.addAll(supplementReads);
		supplementReads.clear();
		for (final SelectionKey selectionKey : readsNow) {
			try {
				doRead(selectionKey);

			} catch (final Exception e) {
				continue;
			}
		}
	}

	protected void pollSupplementWrites() {

		if (supplementWrites.isEmpty())
			return;
		final List<SelectionKey> writesNow = new ArrayList<>();
		writesNow.addAll(supplementWrites);
		supplementWrites.clear();
		for (final SelectionKey selectionKey : writesNow) {
			try {
				doWrite(selectionKey);

			} catch (final Exception e) {
				continue;
			}
		}

	}
}